<template>
  <div class="login">
    <el-card style="width: 400px">
      <el-form :label-width="'auto'" ref="formRef" :model="formInline" :rules="rules" class="demo-form-inline" style="padding: 10px;">
        <el-form-item label="账号：" prop="user">
          <el-input v-model="formInline.user" placeholder="请输入账号" clearable />
        </el-form-item>

        <el-form-item label="密码：" prop="password">
          <el-input type="password" v-model="formInline.password" placeholder="请输入密码" clearable />
        </el-form-item>

        <el-form-item style="margin-bottom: 0;">
          <div style="width: 100%;text-align: center;">
            <el-button type="primary" size="large" @click="onSubmit">登录</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

  <loadingBar></loadingBar>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance, FormItemRule } from 'element-plus'
import loadingBar from '@/components/loadingBar.vue';
import axios from 'axios'
import demo1  from '../pages/demo1.vue';
console.log('demo1 :>> ', demo1);

const router = useRouter()

const formInline = reactive({
  user: '',
  password: '',
})

const formRef = ref<FormInstance>()

interface Form {
  user: string,
  password: string
}

interface DynimacRoute {
  path: string
  name: string
  component: string
}

type Rules = {
  [K in keyof Form]: Array<FormItemRule>
}

const rules = reactive<Rules>({
  user: [{
    required: true,
    message: '请输入账号',
    type: 'string'
  }],
  password: [{
    required: true,
    message: '请输入密码',
    type: 'string'
  }]
})


const onSubmit = () => {
  formRef.value?.validate((validate: any) => {
    if (validate) {
      // router.push({
      //   path: '/user-index'
      // })
      localStorage.setItem('token', btoa(formInline.password ))
      initRouter()
    }
  })

  const initRouter = () => {
    let modules = import.meta.glob('../pages/**/*.vue')

    axios.get('../route.json?_t=' + Date.now()).then(res => {
      const routes:Array<DynimacRoute> = res.data.routes
      routes.forEach(route => {
        const fileName = `../${route.component}.vue`
        console.log('fileName :>> ', fileName);
        router.addRoute({
          path: route.path,
          name: route.name,
          component: modules[`../${route.component}.vue`]
        })
      });

      const routes1 = router.getRoutes()
      console.log('routes1 :>> ', routes1);

      router.push({
        path: '/demo1'
      })
    })
  }

}
</script>

<style scoped lang="scss">
.login {
  display: flex;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 80px);
}
</style>
